<?php

namespace Frieza\Modules\Creators\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Position\PositionRules;
use Doraemon\model\PrizeTopic;
use Doraemon\model\TopicActivity;
use Doraemon\service\position\AdmOperationModule;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Filter;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class TopicController extends Controller
{
    const ONLINE = 1;
    const WAITING = 2;
    const OFFLINE = 3;
    const ONLINE_AND_WAITING = 4;

    const TOPIC_STATUS_MAP = [
        self::ONLINE => '正在展示',
        self::WAITING => '等待中',
        self::OFFLINE => '下架',
        self::ONLINE_AND_WAITING => '正在展示以及等待中'
    ];

    public function topicList(Request $request, Content $content)
    {
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $search['title'] = $request->input('title');
        $search['topic_id'] = $request->input('topic_id');
        $search['type'] = $request->input('type');
        $search['start'] = $request->input('time')['start'];
        $search['end'] = $request->input('time')['end'];

        $where = $this->buildWhere($search);
        $total = PrizeTopic::count($where);
        $where['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $prizeTopics = PrizeTopic::getAll($where);
        if ($prizeTopics) {
            $topicIds = array_column($prizeTopics, 'topic_id');
            $topicList = TopicActivity::getAllList($topicIds);
            //用户分群
            $list = array_column($prizeTopics, 'id');
            $userProfiles = AdmOperationModule::getPositionRulesById($list, PositionRules::MODULE_TYPE_CREATORS_TOPIC);
            foreach ($prizeTopics as $key => $topic) {
                $prizeTopics[$key]['user_profile'] = $userProfiles[$topic['id']];
                $prizeTopics[$key]['title'] = $topicList[$topic['topic_id']]['title'];
                $now = time();
                if ($now >= $topic['start_time'] && $now <= $topic['end_time']) {
                    $prizeTopics[$key]['topic_status'] = self::ONLINE;
                } elseif ($now > $prizeTopics[$key]['end_time']) {
                    $prizeTopics[$key]['topic_status'] = self::OFFLINE;
                } elseif ($now < $topic['start_time']) {
                    $prizeTopics[$key]['topic_status'] = self::WAITING;
                }
                $prizeTopics[$key]['start_time'] = date('Y-m-d H:i:s', $topic['start_time']);
                $prizeTopics[$key]['end_time'] = date('Y-m-d H:i:s', $topic['end_time']);
            }
        }

        $gridModel = new pGridDataModel($prizeTopics, $total, ['perPage' => $pageSize]);
        $gridList = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->filter(function (Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(6, function (Filter $filter) {
                    $filter->equal('topic_id', '话题ID');
                    $filter->equal('title', '标题');
                    $filter->equal('type', '类型')->radio([
                        self::OFFLINE => self::TOPIC_STATUS_MAP[self::OFFLINE],
                        self::ONLINE_AND_WAITING => self::TOPIC_STATUS_MAP[self::ONLINE_AND_WAITING]
                    ])->default(self::ONLINE_AND_WAITING);
                });
                $filter->column(6, function (Filter $filter) {
                    $filter->between('time', '下线时间范围')->date();
                });
                $filter->expand();
            });

            $grid->column('id', 'ID')->sort();
            $grid->column('topic_id', '话题ID');
            $grid->column('title', '话题名称');
            $grid->column('content', '副标题');
            $grid->column('topic_status', '状态')->display(function ($title, Grid\Column $column) {
                switch ($this->topic_status) {
                    case self::ONLINE:
                        return '<span class="label label-success">' . self::TOPIC_STATUS_MAP[self::ONLINE] . '</span><div class="p-1"></div><span class="label label-success">' . $this->start_time . '</span><div class="p-1"></div><span class="label label-success">' . $this->end_time . '</span>';
                    case self::WAITING:
                        return '<span class="label label-warning">' . self::TOPIC_STATUS_MAP[self::WAITING] . '</span><div class="p-1"></div><span class="label label-warning">' . $this->start_time . '</span><div class="p-1"></div><span class="label label-warning">' . $this->end_time . '</span>';
                    case self::OFFLINE:
                        return '<span class="label label-danger">' . self::TOPIC_STATUS_MAP[self::OFFLINE] . '</span><div class="p-1"></div><span class="label label-danger">' . $this->start_time . '</span><div class="p-1"></div><span class="label label-danger">' . $this->end_time . '</span>';
                }
            });
            $grid->column('user_profile', '分群信息')->userProfile();
            $grid->column('operator', '操作者')->display(function ($operator) {
                return Admin::user()->find($operator)->name;
            });
            $grid->actions(function ($action) {
            });
        });
        $tab = new Tab();
        $tab->add('有奖话题', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('有奖话题')
            ->description(' ')
            ->breadcrumb(['text' => '有奖话题']);
    }

    public function create(Content $content)
    {
        $tab = new Tab();
        $form = new Form();
        $form->text('topic_id', '话题ID')->required();
        $form->text('content', '副标题')->required();
        $form->dateTimeRange('start_time', 'end_time', '线上时间范围');
        $form->userProfile('user_profile', '用户分群')->generate();
        $form->action('/admin/creators/topic/save');
        $tab->add('添加有奖话题', $form, true);
        $content->header('添加话题ID')
            ->breadcrumb(
                ['text' => '有奖话题', 'url' => '/creators/topic/list'],
                ['text' => '添加话题ID',]
            )
            ->row($tab);
        return $content;
    }

    public function save(Request $request)
    {
        $params = $request->all();
        $params['start_time'] = strtotime($params['start_time']);
        $params['end_time'] = strtotime($params['end_time']);
        $userProfile = $params['user_profile'];
        $data = [
            'data_status' => PrizeTopic::STATUS_NORMAL,
            'addtime' => time(),
            'edittime' => time(),
            'operator' => Admin::user()->id,
            'topic_id' => $params['topic_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
            'content' => $params['content']
        ];

        $Id = PrizeTopic::addTopic($data);
        //用户分群
        if ($Id) {
            AdmOperationModule::addUserProfile($Id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_TOPIC);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);
        if ($Id) {
            return redirect('/admin/creators/topic/list')->with(compact('success'));
        }
        return redirect('/admin/creators/topic/list')->with(compact('error'));
    }

    public function edit(Content $content, $id)
    {
        $tab = new Tab();
        $where = ['id' => $id];
        $list = PrizeTopic::get('*', $where);
        $data = ['topic_id' => $list['topic_id'],
            'start_time' => date('Y-m-d', $list['start_time']),
            'end_time' => date('Y-m-d', $list['end_time']),
            'content' => $list['content'],
            "user_profile" => AdmOperationModule::getPositionRulesById($id, PositionRules::MODULE_TYPE_CREATORS_TOPIC, true)
        ];

        $form = new Form($data);
        $form->text('topic_id', '话题Id')->required();
        $form->text('content', '副标题')->required();
        $form->dateTimeRange('start_time', 'end_time', '线上时间范围');
        $form->userProfile('user_profile', '用户分群')->generate();
        $tab->add('修改话题ID', $form, true);
        $form->action('/admin/creators/topic/' . $id . '/update');
        $content->header('修改话题ID')
            ->breadcrumb(
                ['text' => '有奖话题', 'url' => '/creators/topic/list'],
                ['text' => '修改话题ID',]
            )
            ->row($tab);
        return $content;
    }

    public function editSave(Request $request, $id)
    {
        $params = $request->input();
        $userProfile = $params['user_profile'];
        $params['start_time'] = strtotime($params['start_time']);
        $params['end_time'] = strtotime($params['end_time']);
        $data = [
            'edittime' => time(),
            'topic_id' => $params['topic_id'],
            'start_time' => $params['start_time'],
            'end_time' => $params['end_time'],
            'content' => $params['content']
        ];
        if ($id) {
            $result = PrizeTopic::updataById($data, $id);
            AdmOperationModule::addUserProfile($id, $userProfile, PositionRules::MODULE_TYPE_CREATORS_TOPIC);
        }
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);
        if ($result) {
            return redirect('/admin/creators/topic/list')->with(compact('success'));
        }
        return redirect('/admin/creators/topic/list')->with(compact('error'));
    }

    public function deleteById($id)
    {
        $result = PrizeTopic::deleteById($id);
        $success = new MessageBag([
            'title' => '操作成功'
        ]);
        $error = new MessageBag([
            'title' => '操作失败'
        ]);

        if ($result) {
            return redirect('/admin/creators/topic/list')->with(compact('success'));
        }
        return redirect('/admin/creators/topic/list')->with(compact('error'));
    }

    public function topicWeight(Request $request)
    {
        $sort = $request->input('sort');
        if (isset($sort)) {
            PrizeTopic::weight($sort);
        }
    }

    private function buildWhere($search = [])
    {
        $where = [];
        if ($search['type'] == self::OFFLINE) {
            $where['end_time[<]'] = time();
        } else {
            $where['end_time[>]'] = time();
        }
        if ($search['title']) {
            $ids = TopicActivity::getTopicsByTitle($search['title'],'id');
            $where['topic_id'] = $ids ?: " ";
        }
        if ($search['topic_id']) {
            $where['topic_id[~]'] = $search['topic_id'];
        }
        if ($search['time']['start']) {
            $where['start_time[>]'] = strtotime($search['start']);
        }
        if ($search['time']['end']) {
            $where['end_time[<]'] = strtotime($search['end']);
        }
        $where['data_status'] = PrizeTopic::STATUS_NORMAL;
        $where['ORDER'] = ['weight' => 'ASC'];
        return $where;
    }

}